﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Pattern01单例模式
{
    public sealed class Counter
    {
        public Counter() 
        {
            CreateTime = DateTime.Now;
            Console.WriteLine($"实例化时间：{CreateTime}");
        }

        public DateTime CreateTime { get;private set; }
        private static Counter singleton = null;
        
        /* 只能适用单线程
        
        public static Counter GetSingleton()
        {
            if (singleton == null)
            {
                singleton = new Counter();
            }

            return singleton;
        }*/


        //第2种，适用多线程
        //public static Counter Instance = new Counter();

        private static readonly object locker = new object();

        //第3种， 加锁，能用，性能差
        public static Counter Singleton
        {
            get
            {
                lock (locker)
                {
                    if (singleton == null)
                    {
                        singleton = new Counter();
                    }

                    return singleton;
                }
            }
        }

        //第4种方案 双判断锁,加强性能
        public static Counter Singleton2
        {
            get
            {
                if (singleton == null)
                {
                    lock (locker)
                    {
                        if (singleton == null)
                        {
                            singleton = new Counter();
                        }                        
                    }
                }

                return singleton;

            }
        }

        //第5种 Lazy 懒加载

        private static readonly Lazy<Counter> lazyInstance = new Lazy<Counter>(() => new Counter());
        public static Counter LazyInstance => lazyInstance.Value;

        //第6种 IOC容器单例注册 prism

        
    }
}
